// app/plugin/tcp/server.js
const net = require('net');

class TcpServer {
    constructor(config) {
        this.config = config;
        this.server = null;
    }

    async start() {
        return new Promise((resolve, reject) => {
            this.server = net.createServer((socket) => {
                // 处理客户端连接
                socket.on('data', (data) => {
                    // 处理接收到的数据
                    console.log(`Received: ${data.toString()}`);
                    socket.write('Hello from TCP Server\n');
                });

                socket.on('end', () => {
                    // 处理连接关闭
                    console.log('Client disconnected');
                });

                socket.on('error', (err) => {
                    // 处理错误
                    console.error(`Socket error: ${err.message}`);
                });
            });

            this.server.listen(this.config.port, (err) => {
                if (err) {
                    reject(err);
                } else {
                    resolve();
                }
            });
        });
    }

    async stop() {
        return new Promise((resolve) => {
            if (this.server) {
                this.server.close(() => {
                    resolve();
                });
            } else {
                resolve();
            }
        });
    }
}

module.exports = TcpServer;
